package pers.wk.queues.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

import java.text.MessageFormat;

/**
 * 工作队列-消费者（轮询）
 */
public class Customer04 {

    private static String queueName = MQConfig.QueueNames.WORK_QUEUE_NAME;

    public static void main(String[] args) {
        //1.ConnectionFactory
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            //生产者定义了，这里可不写
            channel.queueDeclare(queueName,
                    false, false, false, null);
            System.out.println("工作队列-消费者04，启动。。。");

            Channel channelTemp = channel;
            channelTemp.basicQos(1);
            channelTemp.basicConsume(queueName, true, (consumerTag, message) -> {
                //@FunctionalInterface DeliverCallback
                System.out.println(MessageFormat.format("工作队列04-消费者获取消息：【{1}】{0}",
                        new String(message.getBody(), "UTF-8")
                        , message.getEnvelope().getDeliveryTag()));
            }, (consumerTag) -> {
                //@FunctionalInterface CancelCallback
            });

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }
    }
}
